<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <div class=" input-box mb20">
          <input type="text" class="input" v-model="keyword" placeholder="请输入员工姓名" />
          <span class="span" @click="keywordQuery"><i class="el-icon-search"/></span>
        </div>
        <el-form-item>
          <el-button plain round icon="el-icon-plus"  v-perm="'employee/add'" type="primary" @click="handleAdd">新增员工</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="employeeLists" highlight-current-row v-loading="listLoading"
              @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60" label="编号">
      </el-table-column>
      <el-table-column prop="adminName" label="员工姓名" width="120" sortable>
      </el-table-column>
      <el-table-column prop="account" label="账号名称" width="120" sortable>
      </el-table-column>
      <el-table-column prop="company" label="所属公司" width="100" sortable>
      </el-table-column>
      <el-table-column prop="duties"align="center" label="职务" width="100" sortable>
      </el-table-column>
      <el-table-column prop="rolesId" label="角色" width="120" >
        <template slot-scope="scope ">
          <span style="color: #1d8ce0 ;white-space: normal; display: block;">
          {{ getRoleNames(scope.row.rolesId) }}
            </span>
        </template>

      </el-table-column>
      <el-table-column prop="loginTime"align="center" label="登陆时间" width="100" sortable>
      </el-table-column>
      <el-table-column prop="loginIp" align="center"label="登陆ip" width="150" sortable>
      </el-table-column>
      <el-table-column align="center"label="操作">
        <template scope="scope">
          <el-button v-perm="'employee/updatePass'" type="info" size="small" @click="handleEditPasw(scope.$index, scope.row)"v-if="scope.row.id !== 5">修改密码</el-button>
          <el-button  v-perm="'employee/update'" type="info" size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button  v-perm="'employee/del'" type="danger" size="small" @click="handleDel(scope.$index, scope.row)" v-if="scope.row.id !== 5">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-pagination layout="total, sizes, prev, pager, next, jumper"
                     :page-sizes="[5, 10, 20, 50]"
                     @current-change="handleCurrentChange"
                     @size-change="handleSizeChange"
                     :current-page="currentPage" :page-size="pageSize"
                     :total="totals" style="float:right; margin-right: 40px;"  >
      </el-pagination>
    </el-col>

    <!--编辑界面-->
    <el-dialog title="编辑" :visible.sync="editFormVisible" :close-on-click-modal="false">
      <el-form :model="editForm" label-width="110px" :rules="editFormRules" ref="editForm">
        <el-form-item label="员工名称" prop="adminName">
          <el-input v-model="editForm.adminName"  auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="账号" prop="account">
          <el-input v-model="editForm.account"  auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="editForm.phone" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="所属部门" prop="departmentId">
          <el-select v-model="editForm.departmentId" placeholder="请选择">
            <el-option v-for="item in departments"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属角色" prop="rolesId">
          <el-select v-model="editForm.rolesId" multiple placeholder="请选择">
            <el-option
                v-for="item in roleList"
                :label="item.name"
                :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.id }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>

    <!--修改密码界面-->
    <el-dialog title="修改密码" :visible.sync="editPaswFormVisible" :close-on-click-modal="false">
      <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
        <el-form-item label="员工名称" prop="adminName">
          <el-input v-model="editForm.adminName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="账号" prop="adminName">
          <el-input v-model="editForm.adminName" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="新密码" prop="newpassword">
          <el-input v-model="editForm.newpassword" auto-complete="off" style="width: 220px;" show-password></el-input>
          <el-tooltip effect="dark" content="密码长度至少8位，包含大小写字母和字符" placement="top">
            <i class="el-icon-info"></i>
          </el-tooltip>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editPaswFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit1" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>


    <!--新增界面-->
    <el-dialog title="新增" :visible.sync="addFormVisible" :close-on-click-modal="false">
      <el-form :model="addForm" label-width="100px" :rules="addFormRules" ref="addForm">
        <el-form-item label="员工名称" prop="adminName">
          <el-input v-model="addForm.adminName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="账号" prop="account">
          <el-input v-model="addForm.account" auto-complete="off" @blur="checkAccount"></el-input>
          <el-tooltip v-if="duplicateType === 'account'" content="账号已重复" placement="right">
            <span style="color: #ff4949;">账号已重复，请重新输入</span>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="addForm.phone" auto-complete="off" @blur="checkPhone"></el-input>
          <el-tooltip v-if="duplicateType === 'phone'" content="手机号已重复" placement="right">
            <span style="color: #ff4949;">手机号已重复，请更换手机号</span>
          </el-tooltip>
        </el-form-item>
<!--        <el-form-item label="员工图片" prop="avatar">
          <el-input v-model="addForm.avatar" auto-complete="off"></el-input>
        </el-form-item>-->
        <el-form-item label="所属部门" prop="departmentId">
          <el-select v-model="addForm.departmentId" placeholder="请选择">
            <el-option v-for="item in departments"
                       :label="item.name"
                       :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.id }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="密码" prop="password"  >
          <el-input v-model="addForm.password" auto-complete="off" style="width: 220px;" show-password></el-input>
          <el-tooltip effect="dark" content="密码长度至少8位，包含大小写字母和字符" placement="top">
            <i class="el-icon-info"></i>
          </el-tooltip>
        </el-form-item>

      <el-form-item label="所属角色" prop="rolesId">
        <el-select v-model="addForm.rolesId" multiple placeholder="请选择">
          <el-option
              v-for="item in roleList"
              :label="item.name"
              :value="item.id">
            <span style="float: left">{{ item.name }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.id }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click.native="addFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import util from '../../common/js/util'
//import NProgress from 'nprogress'
// import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';

export default {
  data() {
    return {
      duplicateType:'',
      //1.分页查询的相关数据
      employeeLists: [],
      totals: '',
      currentPage: 1,
      pageSize: 5,
      pageSizes: [5,10, 20, 50], // 可选择的每页条数
      listLoading: false,
      sels: [],//列表选中列

      //2.高级查询相关数据
      keyword: '',

      editFormVisible: false,//编辑界面是否显示
      editPaswFormVisible:false,//修改密码界面不显示
      editLoading: false,
      editFormRules: {
        adminName: [
          {required: true, message: '请输入管理员名', trigger: 'blur'}
        ],
        password: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 8, message: '密码长度至少为8位', trigger: 'blur' },
          { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]+$/, message: '密码必须包含大小写字母、数字和特殊字符', trigger: 'blur' }
        ],
        phone:[
          {required: true, message:'请输入手机号码',trigger:'blur'},
        ],
        newpassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 8, message: '密码长度至少为8位', trigger: 'blur' },
          { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]+$/, message: '密码必须包含大小写字母、数字和特殊字符', trigger: 'blur' }
        ],
      },
      //编辑界面数据
      editForm: {
        id: null,
        adminName: '',
        account:'',
        company: '',
        duties:'',
        loginIp:'',
        loginTime:'',
        state: 1,
        salt:'',
        phone:'',
        password: '',
        newpassword:'',
        // logininfoId: '',
        departmentId: '',
        shopId: '',
        rolesId:''
      },

      addFormVisible: false,//新增界面是否显示
      addLoading: false,
      addFormRules: {
       adminName: [
          {required: true, message: '请输入用户名', trigger: 'blur'}
        ],
        phone: [
          {required: true, message: '请输入手机号码', trigger: 'blur'}
        ],
        account: [
          {required: true, message: '请输入账户名', trigger: 'blur'}
        ],
        password: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 8, message: '密码长度至少为8位', trigger: 'blur' },
          { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]+$/, message: '密码必须包含大小写字母、数字和特殊字符', trigger: 'blur' }
        ],
      },

      //新增界面数据
      addForm: {

      },
      //员工所属部门
      departments: [],
      //员工所属店铺
      shops: [],
      //角色
      roleList: []

    }
  },
  methods: {
    getRoleNames(rolesId) {
      // 根据 rolesId 查询角色名字
      const roleNames = rolesId.map(roleId => this.roleList.find(role => role.id === roleId).name);
      return roleNames.join('      ');
    },
    //当用户输入的手机号账号有重复时的验证
    async checkAccount() {
      const account = this.addForm.account;
      if (!account) {
        return;
      }

      try {
        const response = await this.$http.post('/employee/checkDuplicate', { type: 'account', value: account });
        this.duplicateType = response.data.isDuplicate ? 'account' : '';
      } catch (error) {
        console.error('Error checking duplicate for account:', error);
        this.duplicateType = ''; // 假设发生错误时不处理重复
      }
    },

    async checkPhone() {
      const phone = this.addForm.phone;
      if (!phone) {
        return;
      }

      try {
        const response = await this.$http.post('/employee/checkDuplicate', { type: 'phone', value: phone });
        this.duplicateType = response.data.isDuplicate ? 'phone' : '';
      } catch (error) {
        console.error('Error checking duplicate for phone:', error);
        this.duplicateType = ''; // 假设发生错误时不处理重复
      }
    },
    handlePageSizeChange(val) {
      this.pageSize = val;
      this.getEmployeeLists();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1; // 重置当前页码为1
      this.getEmployeeLists();
    },
    //1.分页获取用户列表
    getEmployeeLists() {
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.keyword
      };
      this.listLoading = true;
      this.$http.post("/employee", para).then((res) => {
        this.totals = res.data.total;
        this.employeeLists = res.data.records;
        this.listLoading = false;
      }).catch(res => {
        this.$message.error("系统繁忙，请稍后重试!!!【400,404】")
      });
    },

    //2.点击分页实现
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.getEmployeeLists();
    },

    //3.关键字查询
    keywordQuery() {
      //假如当前页不在第一页，防止高级查询没有那么多页的时候出现空数据的问题
      this.currentPage = 1;
      this.getEmployeeLists();
    },

    //4.修改用户状态
    handleDisable: function (row) {
      this.$confirm('确认禁用该用户吗?禁用后该账户不可再进行操作！', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.put("/employee/" + row.id).then(res => {
          if (res.data.success) {
            //计算总页数
            let totalPage = Math.ceil(this.total / this.pageSize);
            // 当删除最后一页的最后一条数据，并且当前不是第一页，就让当前页-1
            if (this.currentPage == totalPage && (this.total - 1) % this.pageSize == 0 && this.currentPage != 1) {
              this.currentPage = this.currentPage - 1;
            }
            this.$message({
              message: '修改成功',
              type: 'success'
            });
            this.getEmployeeLists();
          } else {
            this.$message.error("系统繁忙，请稍后重试!!!【500】");
          }
          this.listLoading = false;
        }).catch(res => {
          this.$message.error("系统繁忙，请稍后重试!!!【400,404】");
        })
      }).catch(() => {
      });
    },

    //5.删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.delete("/employee/" + row.id).then(res => {
          if (res.data.success) {
            //计算总页数
            let totalPage = Math.ceil(this.total / this.pageSize);
            // 当删除最后一页的最后一条数据，并且当前不是第一页，就让当前页-1
            if (this.currentPage == totalPage && (this.total - 1) % this.pageSize == 0 && this.currentPage != 1) {
              this.currentPage = this.currentPage - 1;
            }
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.getEmployeeLists();
          } else {
            this.$message.error("系统繁忙，请稍后重试!!!【500】");
          }
          this.listLoading = false;
        }).catch(res => {
          this.$message.error("系统繁忙，请稍后重试!!!【400,404】");
        })
      }).catch(() => {
      });
    },

    //6.选项改变时触发
    selsChange: function (sels) {
      this.sels = sels;
    },

    //7.批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id).toString();
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch("/employee", ids).then(res => {
          if (res.data.success) {
            //处理当前页
            //算总页数
            let totalPage = Math.ceil(this.total / this.pageSize);
            //当删除最后一页的所有数据，并且不是第一页，就让当前页-1
            if (this.currentPage == totalPage && (this.total - this.sels.length) % this.pageSize == 0 && this.currentPage != 1) {
              this.currentPage = this.currentPage - 1;
            }
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.getEmployeeLists();
          } else {
            this.$message.error("系统繁忙，请稍后重试!!!【500】");
          }
          this.listLoading = false;
        }).catch(res => {
          this.$message.error("系统繁忙，请稍后重试!!!【400,404】");
        })
      }).catch(() => {
      });

    },

    //8.显示编辑界面
    handleEdit: function (index, row) {
      this.editForm = Object.assign({}, row);
      this.editFormVisible = true;
      this.getDepartments();
      // this.getShops();
      this.getRoles()

    },
    //8-1，显示修改密码界面
    handleEditPasw: function (index,row){
      this.editForm = Object.assign({}, row);
      this.editPaswFormVisible = true;
      //this.getDepartments();
      // this.getShops();
      this.getRoles()
    },

    //9.显示新增界面
    handleAdd: function () {
      this.addForm = {
        state: 1
      };
      this.addFormVisible = true;
      this.getDepartments();
      this.getShops();
      this.getRoles()
    },

    //10.提交编辑数据
    editSubmit: function () {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true;
            this.editForm.password=this.editForm.newpassword;
            let para = Object.assign({}, this.editForm);
            this.$http.put("/employee", para).then(res => {
              if (res.data.success) {
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
                this.$refs['editForm'].resetFields();
              } else {
                this.$message.error("系统繁忙，请稍后重试!!!【500】");
              }
              this.editLoading = false;
              this.editFormVisible = false;
              this.getEmployeeLists();
            });
          });
        }
      });
    },
    editSubmit1: function () {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true;
            this.editForm.password=this.editForm.newpassword;
            let para = Object.assign({}, this.editForm);
            this.$http.put("/employee", para).then(res => {
              if (res.data.success) {
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
                this.$refs['editForm'].resetFields();
              } else {
                this.$message.error("系统繁忙，请稍后重试!!!【500】");
              }
              this.editLoading = false;
              this.editPaswFormVisible = false;
              this.getEmployeeLists();
            });
          });
        }
      });
    },

    //获得所有部门
    getDepartments() {
      this.$http.get("/department").then(res=>{
        this.departments=res.data;
      })
    },
    //获得所有店铺
    getShops(){
      this.$http.get("/shop").then(res=>{
        this.shops=res.data;
      })
    },

    //11.新增
    addSubmit: function () {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true;
            let para = Object.assign({}, this.addForm);
          //  para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
            this.$http.put("/employee", para).then(res => {

              if (res.data.success) {
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
                this.$refs['addForm'].resetFields();
              } else {
                this.$message.error("系统繁忙，请稍后重试!!!【500】");
              }
              this.addLoading = false;
              this.addFormVisible = false;
              this.getEmployeeLists();
            });
          });
        }
      });
    },
    //.获取角色们
    getRoles() {
      this.$http.get("/role").then(res => {
        this.roleList = res.data;
      })
    },
  },
  mounted() {
    this.getEmployeeLists();
    this.getRoles();
  }
}

</script>

<style scoped>

</style>